<?php

namespace api\mobile;

use think\facade\Db;
use app\common\model\Mobile;

class BaseModel
{
    const SUCCESS = 1;          // 下单成功
    const FAIL = 2;             // 下单失败
    const LACK_OF_MONEY = 3;    // 余额不足
    const NEED_RETRY = 4;       // 需要重试，不要修改订单状态
    const RECHARGE_SUCCESS = 5; // 充值成功【目前就慧仕有此状态】
    const RECHARGE_FAIL = 6;    // 充值失败【空号，携号转网，虚拟号码，直接失败，不再重试】
    const NEED_CONFIRM = 21;    // 异常订单，需要人工确认

    protected $info = []; // 供应商参数
    protected $notifyUrl = ''; // 异步通知回调地址
    protected $error = '';

    public function __construct($info)
    {
        $this->info = $info;
        $this->notifyUrl = env('app.api_url') . '/api/mobile_notify/handle/mobileSupplierId/' . $info['id'];
    }

    public function getError()
    {
        return $this->error;
    }

    /**
     * 下单，直接成功
     */
    public function handleSuccess($id, $supplierOrderNo = '')
    {
        $order = Db::name('mobile_order')
            ->where('id', $id)
            ->find();
        if (empty($order)) {
            $this->error = '订单不存在 ' . $id;

            return false;
        }

        if ($order['supplier_status'] == 3) {
            $this->error = '已经成功过 ' . $id;

            return false;
        }

        if ($order['supplier_status'] != 1) {
            $this->error = '订单状态有误：' . $order['supplier_status'] . ' ' . $id;

            return false;
        }

        $update = [
            'supplier_status' => 3,
            'supplier_order_no' => $supplierOrderNo,
            'finish_time' => time(),
        ];

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $this->error = '订单更新失败: ' . $id . '。' . $e->getMessage();

            return false;
        }

        return true;
    }

    /**
     * 下单，直接失败
     */
    public function handleFail($id, $remark)
    {
        $order = Db::name('mobile_order')
            ->where('id', $id)
            ->find();
        if (empty($order)) {
            $this->error = '订单不存在 ' . $id;

            return false;
        }

        if ($order['supplier_status'] == 4) {
            $this->error = '已经失败过 ' . $id;

            return false;
        }

        if ($order['supplier_status'] != 1) {
            $this->error = '订单状态有误：' . $order['supplier_status'] . ' ' . $id;

            return false;
        }
        if ($order['refund_status'] != 1) {
            $this->error = '订单退款状态有误：' . $order['refund_status'] . ' ' . $id;

            return false;
        }

        $update = [
            'supplier_status' => 4,
            'refund_status' => 2,
            'remark' => $remark,
            'finish_time' => time(),
        ];

        Db::startTrans();
        try {
            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $this->error = '订单更新失败: ' . $id . '。' . $e->getMessage();

            return false;
        }

        return true;
    }

    /**
     * 测试环境，随机返回下单结果
     */
    protected function testRandomResult()
    {
        $statusMap = [1, 2, 5, 6];
        $status = $statusMap[random_int(0, 3)];
        $supplier_order_no = time();
        $remark = '测试环境模拟结果：' . $status;

        // 模拟接口请求延时
        usleep(210000);

        return compact('status', 'supplier_order_no', 'remark');
    }
}
